package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.StockMapper;
//import com.mall.order.dto.CartProductDto;
import com.mall.shopping.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {

		CreateOrderContext orderContext = (CreateOrderContext) context;

		List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
		List<Long> productIds = new ArrayList<>();

		if (CollectionUtils.isEmpty(productIds)){
			for (CartProductDto cartProductDto : cartProductDtoList) {

				//在这里给List<id>赋值，convert没有赋值
				productIds.add(cartProductDto.getProductId());
			}
		}

		//查询对应id的商品库存并检验
		List<Stock> stocksList = stockMapper.findStocksForUpdate(productIds);
		if (CollectionUtils.isEmpty(stocksList) || stocksList.size() != productIds.size()){
			log.info("库存或部分库存未初始化");
			throw new BizException("库存或部分库存未初始化");
		}

		for (Stock stock : stocksList) {
			if (stock.getStockCount() < stock.getLockCount()){
				log.info("库存不足 {} < {}",stock.getStockCount(),stock.getLockCount());
				throw new BizException("库存不足");
			}
			for (CartProductDto cartProductDto : cartProductDtoList) {
				//判断购物车商品数量是否超过限购，是否库存充足
				if (stock.getRestrictCount() < cartProductDto.getProductNum()){
					//System.out.println("restrict"+stock.getRestrictCount());
					//System.out.println("ProductNum"+cartProductDto.getProductNum());
					log.info("超过限购数量 {} > {}",cartProductDto.getProductNum(),stock.getRestrictCount());
					throw new BizException("超过限购数量");
				}
			}
		}
		//校验合格后更新库存
		for (CartProductDto cartProductDto : cartProductDtoList) {
			Long id = cartProductDto.getProductId();
			Long num = cartProductDto.getProductNum();
			Stock stock = new Stock();
			stock.setItemId(id);//商品id
			stock.setLockCount(num.intValue());//锁定库存 num
			stock.setStockCount(-num);//可用库存-num

			stockMapper.updateStock(stock);
		}

		return true;
	}
}